<?php

namespace App\Formats;

use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Models\Field\TopicField;
use App\Models\Select\TopicSelect;

class TopicFormat extends BaseFormat
{
    public static function getTargetTopicArr($targetIds, $selectScene = TopicSelect::SELF_LIST)
    {
        $targetIds = (array)$targetIds;
        $result = [];

        // 获取主体_话题关联记录
        $targetNotes = repository()->TopicRepository->getTargetTopics($targetIds);
        $topicIdList = ArrayHelper::getColumn($targetNotes, 'topic_id');

        /**
         * 获取话题ID
         * 注意：
         *  1.sys_target_topic中的topic_id是以逗号隔开的
         */
        $topicIdArr = [];
        foreach ($topicIdList as $topicIdInfo) {
            $topicIdArr = ArrayHelper::merge($topicIdArr, explode(',', $topicIdInfo));
        }
        $topicIdArr = collect($topicIdArr)->unique()->values()->toArray();

        // 获取话题列表
        $topicIdTable = IdBuilder::getSubTable($topicIdArr);
        $targetNotes = ArrayHelper::indexByGroups($targetNotes, null, 'target_id');
        $topicArr = [];
        foreach ($topicIdTable as $tableCount => $topicIdArr) {
            $models = repository()->TopicRepository->getTopicByTableCount($tableCount, $topicIdArr, $selectScene);
            $topicArr = ArrayHelper::merge($topicArr, $models);
        }
        $topicArr = ArrayHelper::index($topicArr, 'topic_id');

        // 组装结果
        foreach ($targetIds as $targetId) {
            $topics = [];
            if (!empty($targetNotes[$targetId])) {
                foreach ($targetNotes[$targetId] as $targetTopic) {
                    foreach (explode(',', $targetTopic->topic_id) as $topicId) {
                        if (isset($topicArr[$topicId])) {
                            $topics[] = $topicArr[$topicId]->commonFormat(TopicField::NOTE_DETAIL);
                        }
                    }
                }
                $result[$targetId] = $topics;
            }

        }

        return $result;
    }
}
